package com.binguo.util;

public class IOUUtil {

    public static double caculateIOU(double a_x1, double a_y1, double a_x2, double a_y2,
                                     double b_x1, double b_y1, double b_x2, double b_y2
    ) {

        double x1 = a_x1;
        double y1 = a_y1;
        double width1 = a_x2 - a_x1;
        double height1 = a_y2 - a_y1;

        double x2 = b_x1;
        double y2 = b_y1;
        double width2 = b_x2 - b_x1;
        double height2 = b_y2 - b_y1;

        double endx = Math.max(x1 + width1, x2 + width2);
        double startx = Math.min(x1, x2);
        double width = width1 + width2 - (endx - startx);

        double endy = Math.max(y1 + height1, y2 + height2);
        double starty = Math.min(y1, y2);
        double height = height1 + height2 - (endy - starty);

        double ratio;
        if (width <= 0 || height <= 0) {
            ratio = 0;
        } else {
            double area = width * height;
            double area1 = width1 * height1;
            double area2 = width2 * height2;
            ratio = new Double(area)/new Double(area1);
        }
        return ratio;
    }

    public static double caculateIOU(int a_x1, int a_y1, int a_x2, int a_y2,
                                  int b_x1, int b_y1, int b_x2, int b_y2
    ) {

        int x1 = a_x1;
        int y1 = a_y1;
        int width1 = a_x2 - a_x1;
        int height1 = a_y2 - a_y1;

        int x2 = b_x1;
        int y2 = b_y1;
        int width2 = b_x2 - b_x1;
        int height2 = b_y2 - b_y1;

        int endx = Math.max(x1 + width1, x2 + width2);
        int startx = Math.min(x1, x2);
        int width = width1 + width2 - (endx - startx);

        int endy = Math.max(y1 + height1, y2 + height2);
        int starty = Math.min(y1, y2);
        int height = height1 + height2 - (endy - starty);

        double ratio;
        if (width <= 0 || height <= 0) {
            ratio = 0;
        } else {
            int area = width * height;
            int area1 = width1 * height1;
            int area2 = width2 * height2;
            ratio = new Double(area)/new Double(area1);
        }
        return ratio;
    }
}
